package co.edu.uniandes.sd.mundo;
import java.io.File;
import java.io.FileInputStream;
import java.net.URI;
import java.util.Date;

import net.jxta.document.AdvertisementFactory;
import net.jxta.endpoint.Message;
import net.jxta.endpoint.MessageElement;
import net.jxta.id.IDFactory;
import net.jxta.peergroup.PeerGroup;
import net.jxta.pipe.InputPipe;
import net.jxta.pipe.PipeID;
import net.jxta.pipe.PipeMsgEvent;
import net.jxta.pipe.PipeMsgListener;
import net.jxta.pipe.PipeService;
import net.jxta.platform.NetworkManager;
import net.jxta.protocol.PipeAdvertisement;

public class PipeListener implements PipeMsgListener {
	
	public final static String SOCKET_ID = "urn:jxta:uuid-59616261646162614E5047205032503393B5C2F6CA7A41FBB0F890173088E79404";
	static PeerGroup netPeerGroup = null;
	private final static String TAG = "PipeListenerMsg";
	private final static String FILENAME = "examplepipe.adv";
	private PipeService pipeSvc;
	private PipeAdvertisement pipeAdv;
	private InputPipe pipeIn = null;

	public static void main(String args[]) {
		PipeListener myapp = new PipeListener();
		myapp.startJxta();
		myapp.run();
	}

	// Starts jxta
	private void startJxta() {
		try {
			NetworkManager manager = new NetworkManager(NetworkManager.ConfigMode.ADHOC,"PipeListener",new File(new File(".cache"), "PipeListener").toURI());
			manager.startNetwork();
			netPeerGroup = manager.getNetPeerGroup();
			// create, and Start the default jxta NetPeerGroup
			//netPeerGroup = PeerGroupFactory.newNetPeerGroup();
		} catch (Exception e) {
			// could not instantiate the group, print the stack and exit
			System.out.println("Error: fatal error : group creation failure");
			e.printStackTrace();
			System.exit(1);
		}
		pipeSvc = netPeerGroup.getPipeService();
		System.out.println("Reading in " + FILENAME);
		try {
			FileInputStream is = new FileInputStream(FILENAME);
			pipeAdv = (PipeAdvertisement) AdvertisementFactory
					.newAdvertisement(PipeAdvertisement.getAdvertisementType());
			try{
				PipeID id = (PipeID)IDFactory.fromURI(new URI(SOCKET_ID));
				pipeAdv.setPipeID(id);
				pipeAdv.setName("Mi primer pipe");
				pipeAdv.setType(PipeService.UnicastType);
			}catch (Exception e) {
				e.printStackTrace();
			}
			
			is.close();
		} catch (Exception e) {
			System.out.println("Error: failed to read/parse pipe adv.");
			e.printStackTrace();
			System.exit(-1);
		}
	}

	// create input pipe, and register as a PipeMsgListener to be
	// asynchronously notified of any messaged received on this input pipe
	public void run() {
		try {
			System.out.println("Creating input pipe");
			pipeIn = pipeSvc.createInputPipe(pipeAdv, this);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Error creating input pipe.");
			return;
		}
		if (pipeIn == null) {
			System.out.println("Error: cannot open InputPipe");
			System.exit(-1);
		}
		System.out.println("Waiting for msgs on input pipe");
		while(true);
	}

	// By implementing PipeMsgListener, we define this method to deal with
	// messages as they occur
	public void pipeMsgEvent(PipeMsgEvent event) {
		Message msg = null;
		try {
			// grab the message from the event
			msg = event.getMessage();
			if (msg == null)
				return;
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
		// Get message element with our TAG/name
		MessageElement el = msg.getMessageElement(null, TAG);
		if (el.toString() == null)
			System.out.println("null msg received.");
		else {
			Date date = new Date(System.currentTimeMillis());
			System.out.println("Received message: " + el.toString());
			System.out.println("         message received at: "
					+ date.toString());
		}
	}

}
